<template>
  <div class="app-container">
    <el-card>
      <CategorySelect @getCategoryId="getCategoryId" :show="!isShowTable"></CategorySelect>
    </el-card>
    <el-card style="margin: 20px 0">
      <div v-show="isShowTable">
        <el-button type="primary" icon="el-icon-plus" :disabled="!categoryId3" @click="addAttr">添加属性</el-button>
        <el-table style="width: 100%; margin-top: 20px" border :data="attrList">
          <el-table-column prop="attrId" label="序号" width="60" align="center"></el-table-column>
          <el-table-column prop="attrName" label="属性名称" width="width"></el-table-column>
          <el-table-column prop="prop" label="属性值列表" width="width">
            <template slot-scope="{ row }">
              <el-tag type="success" v-for="attrValue in row.attrValueList" :key="attrValue.id" style="margin: 0 10px">
                {{ attrValue.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <el-button type="warning" size="mini" icon="el-icon-edit" @click="editAttr(row, $index)">修改</el-button>
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteAttr(row, $index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="!isShowTable">
        <el-form :inline="true" label-width="80px">
          <el-form-item label="属性名">
            <el-input placeholder="请输入属性名" v-model="attrInfo.attrName"></el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary" icon="el-icon-plus" @click="addAttrValue" :disabled="!attrInfo.attrName">添加属性值</el-button>
        <el-button @click="isShowTable = true">取消</el-button>
        <el-table style="width: 100%; margin-top: 20px" border :data="attrInfo.attrValueList">
          <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
          <el-table-column prop="attrValueList" label="属性值名称" width="width">
            <template slot-scope="{ row, $index }">
              <el-input
                v-if="row.flag"
                v-model="row.valueName"
                placeholder="请输入属性值名称"
                size="mini"
                :ref="$index"
                @blur="toLook(row, $index)"
                @keyup.native.enter="toLook(row, $index)"
              ></el-input>
              <span v-show="row.flag === false" @click="toEdit(row, $index)">
                {{ row.valueName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <!-- 项目使用的elementUI版本为2.13.2，老版本的绑定时 @onConfirm -->
              <el-popconfirm :title="`确认要删除${row.valueName}?`" @onConfirm="deleteAttrValue(row, $index)">
                <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini"></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="saveAttr" :disabled="attrInfo.attrValueList.length === 0" style="margin-top: 20px">保存</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
// 按需引入lodash中的深拷贝
import cloneDeep from 'lodash/cloneDeep';
export default {
  name: 'Attr',
  components: {},
  data() {
    return {
      categoryId1: '',
      categoryId2: '',
      categoryId3: '',
      isShowTable: true,
      attrList: [],
      attrInfo: {
        attrName: '',
        attrValueList: [],
        categoryId: 0,
        categoryLevel: 3,
      },
    };
  },
  mounted() {},
  methods: {
    getCategoryId({ categoryId, level }) {
      if (level === 1) {
        this.categoryId1 = categoryId;
        // 清楚掉二级和三级id
        this.categoryId2 = '';
        this.categoryId3 = '';
      } else if (level === 2) {
        this.categoryId2 = categoryId;
        this.categoryId3 = '';
      } else {
        this.categoryId3 = categoryId;
        // 发送请求获取平台属性数据
        this.getAttrList();
      }
    },
    // 获取平台属性数据
    async getAttrList() {
      const { categoryId1, categoryId2, categoryId3 } = this;
      let result = await this.$API.attr.reqAttrList(categoryId1, categoryId2, categoryId3);
      if (result.code === 200) {
        this.attrList = result.data;
      } else {
        this.$message.error('获取平台属性数据失败');
      }
    },
    // 添加属性
    addAttr() {
      this.attrInfo = {
        attrName: '',
        attrValueList: [],
        categoryId: this.categoryId3,
        categoryLevel: 3,
      };
      this.isShowTable = false;
    },
    // 修改属性
    editAttr(row) {
      this.isShowTable = false;
      // 这里使用深拷贝
      // this.attrInfo = JSON.parse(JSON.stringify(row));
      this.attrInfo = cloneDeep(row);
      this.attrInfo.attrValueList.forEach((item) => {
        // 给每个属性值对象添加一个flag属性，控制文本框与span的切换
        this.$set(item, 'flag', false);
      });
    },
    // 删除属性
    deleteAttr(row) {
      console.log(row);
    },
    addAttrValue() {
      // attrId是属性值id，目前没有带给服务器为undefined
      this.attrInfo.attrValueList.push({
        attrId: this.attrInfo.id, // 如果修改时有attrId带上，添加时则为undefined
        valueName: '',
        flag: true, // 控制文本框的显示与隐藏
      });
      // 添加完文本框自动获取焦点
      this.$nextTick(() => this.$refs[this.attrInfo.attrValueList.length - 1].focus());
    },
    toLook(row) {
      if (row.valueName.trim() === '') {
        this.$message.error('请输入一个正常的属性值');
        return;
      }
      let isRepat = this.attrInfo.attrValueList.some((item) => {
        if (row !== item) {
          return row.valueName === item.valueName;
        }
      });
      if (isRepat) {
        this.$message.error('属性值不能重复');
        return;
      }
      row.flag = false;
    },
    toEdit(row, index) {
      row.flag = true;
      // 获取焦点
      // 点击span，通过v-if渲染成input标签是需要时间的，所以需要使用$nextTick
      this.$nextTick(() => this.$refs[index].focus());
    },
    deleteAttrValue(row, index) {
      this.attrInfo.attrValueList.splice(index, 1);
    },
    saveAttr() {
      // 整理参数
      // 1.如果用户添加很多空属性值，需要过滤
      // fliter会过滤原数组，然后返回一个新的数组
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter((item) => {
        if (item.valueName !== '') {
          delete item.flag;
          return true;
        }
      });
      // 2.如果用户没有填写属性值，不能发送请求
      if (this.attrInfo.attrValueList.length === 0) {
        this.$message.error('至少填写一个属性值');
        return;
      }
      // 3.发送请求
      this.$API.attr.reqAddOrUpdateAttr(this.attrInfo).then((result) => {
        if (result.code === 200) {
          this.$message.success('保存成功');
          this.isShowTable = true;
          this.getAttrList();
        } else {
          this.$message.error('保存失败');
        }
      });
    },
  },
};
</script>

<style scoped></style>
